package com.ruoyi.web.controller.module.survey;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.estate.EstateRoom;
import com.ruoyi.system.domain.module.estate.EstateRoomBangUser;
import com.ruoyi.system.domain.module.estate.EstateUser;
import com.ruoyi.system.domain.module.event.*;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.survey.SurveyQuestion;
import com.ruoyi.system.domain.module.survey.SurveyUserRecord;
import com.ruoyi.system.domain.module.survey.SurveyUserRecordInfo;
import com.ruoyi.system.service.module.estate.IEstateRoomBangUserService;
import com.ruoyi.system.service.module.estate.IEstateRoomService;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.estate.IEstateUserService;
import com.ruoyi.system.service.module.event.*;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.survey.ISurveyQuestionService;
import com.ruoyi.system.service.module.survey.ISurveyService;
import com.ruoyi.system.service.module.survey.ISurveyUserRecordInfoService;
import com.ruoyi.system.service.module.survey.ISurveyUserRecordService;
import com.ruoyi.system.service.system.ISysUserService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 问卷调查的用户填报数据Controller
 *
 * @author ruoyi
 * @date 2021-09-05
 */
@Validated
@Api(value = "问卷调查的用户填报数据控制器", tags = {"问卷调查的用户填报数据管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/survey/record")
public class SurveyUserRecordController extends BaseController {

    private final ISurveyService surveyService;
    private final ISurveyQuestionService surveyQuestionService;
    private final ISurveyUserRecordService surveyUserRecordService;
	private final ISurveyUserRecordInfoService surveyUserRecordInfoService;
	private final IEventPlanTaskInfoService eventPlanTaskInfoService;
	private final IPropertyService propertyService;
	private final IEstateService estateService;
	private final IEstateRoomBangUserService estateRoomBangUserService;
	private final IEstateRoomService estateRoomService;
	private final IEstateUserService estateUserService;
	private final IEventPlanWorkService eventPlanWorkService;
	private final IEventPlanService eventPlanService;
	private final IEventTerminalsService eventTerminalsService;
	private final IEventPatrolPointService eventPatrolPointService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;
    /**
     * 查询问卷调查的用户填报数据列表
     */
    @ApiOperation("查询问卷调查的用户填报数据列表")
    @PreAuthorize("@ss.hasPermi('module:survey_record:list')")
    @GetMapping("/list")
    public TableDataInfo<SurveyUserRecord> list(@Validated SurveyUserRecord surveyUserRecord) {
        QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
        if(surveyUserRecord.getSurveyId()!=null){
            qw.eq("survey_id",surveyUserRecord.getSurveyId());
        }
        if(StrUtil.isNotEmpty(surveyUserRecord.getPhoneNum())){
            qw.eq("phone_num",surveyUserRecord.getPhoneNum());
        }
		qw.orderByDesc("id");
        TableDataInfo<SurveyUserRecord> td = PageUtils.buildDataInfo(surveyUserRecordService.page(PageUtils.buildPage(),qw));
        List<SurveyUserRecord> list = td.getRows();
        list.forEach(record->{
			Estate estate = estateService.findById(record.getEstateId());
			if(estate!=null){
				record.setEstateName(estate.getEstateName());
			}

			Property property = propertyService.findById(record.getPropertyId());
			if(property!=null){
				record.setPropertyName(property.getPropertyName());
			}

			String roomName = "";
			String phoneNum = "";

//				QueryWrapper<EstateRoom> qwRoom = new QueryWrapper<>();
//				qwRoom.like("phone_num", record.getPhoneNum());
			List<EstateRoom> rooms = estateRoomService.getRoomListByUserId(record.getUserId());
			if(CollUtil.isNotEmpty(rooms)){
				for (EstateRoom room : rooms){
					roomName += room.getRoomNo() + " ";
					if(StrUtil.isEmpty(record.getPhoneNum())){
						phoneNum += room.getPhoneNum();
					}
				}
			}
			if(StrUtil.isEmpty(record.getPhoneNum())) {
				record.setPhoneNum(phoneNum);
			}
			record.setRoomName(roomName);
			QueryWrapper<SurveyUserRecordInfo> qwInfo = new QueryWrapper<>();
			qwInfo.eq("record_id",record.getId());
			List<SurveyUserRecordInfo> infoList = surveyUserRecordInfoService.list(qwInfo);
			int p = 0;
			for (SurveyUserRecordInfo info:infoList){
				if (info.getIsImg()!=1){
					if (info.getAnswer().equals(1)){
						p=1;
					}
				}
			}
			record.setYichang(p);
        });
        return td;
    }

	/**
	 * 查询问卷调查的用户填报数据列表
	 */
	@ApiOperation("查询问卷调查的用户填报数据列表")
	@PreAuthorize("@ss.hasPermi('module:survey_record:list')")
	@GetMapping("/listRecordShengcheng")
	public TableDataInfo<SurveyUserRecord> shengcheng(@Validated SurveyUserRecord surveyUserRecord) {
		//查询问题数据
		QueryWrapper<SurveyQuestion> qw1 = new QueryWrapper<>();
		qw1.eq("survey_id",surveyUserRecord.getSurveyId());
		List<SurveyQuestion> questionList = surveyQuestionService.list(qw1);
		QueryWrapper<EstateRoomBangUser> qw = new QueryWrapper<>();
		qw.eq("estate_id",3);
		List<EstateRoomBangUser> list = estateRoomBangUserService.list(qw);
		Collections.shuffle(list);
		for (EstateRoomBangUser user:list){
			SurveyUserRecord record = new SurveyUserRecord();
			record.setSurveyId(surveyUserRecord.getSurveyId());
			record.setPropertyId(1);
			record.setEstateId(user.getEstateId());
			record.setUserId(user.getBangWxUserId());
			QueryWrapper<EstateRoom> qw2 = new QueryWrapper<>();
			qw2.eq("id",user.getRoomId());
			List<EstateRoom> room = estateRoomService.list(qw2);
			if (room.size()>0){
				if (room.get(0).getPhoneNum()!=null){
					record.setPhoneNum(room.get(0).getPhoneNum());
				}else {
					continue;
				}
				if (room.get(0).getRealName()!=null){
					record.setNickName(room.get(0).getRealName());
				}else {
					continue;
				}
			}else {
				continue;
			}
			boolean t = surveyUserRecordService.save(record);
			if (!t){
				continue;
			}
		//生成问题数据
			for (SurveyQuestion question:questionList){
				SurveyUserRecordInfo info = new SurveyUserRecordInfo();
				info.setRecordId(Math.toIntExact(record.getId()));
				info.setQuestionId(Math.toIntExact(question.getId()));
				info.setUserId(user.getBangWxUserId());
				info.setAnswer("0");
				info.setIsImg(0);
				t = surveyUserRecordInfoService.save(info);
				if (!t){
					break;
				}
			}

		};
		return null;
	}

	/**
	 * 通过workID查询问卷调查的用户填报数据列表
	 */
	@ApiOperation("查询问卷调查的用户填报数据列表")
	@PreAuthorize("@ss.hasPermi('module:survey_record:listWork')")
	@GetMapping("/listWork")
	public List<SurveyUserRecord> listWork(@Validated SurveyUserRecord surveyUserRecord) {
		List<SurveyUserRecord> list = new ArrayList<>();
		QueryWrapper<EventPlanTaskInfo> qwTask = new QueryWrapper<>();
		if (surveyUserRecord.getEventWorkId()!=null){
			qwTask.eq("event_work_id",surveyUserRecord.getEventWorkId());
		}
		List<EventPlanTaskInfo> taskList = eventPlanTaskInfoService.list(qwTask);
		for (EventPlanTaskInfo task:taskList){
			String planName = "";
			if (task.getTargetType()!=null&&task.getTargetId()!=null){
				if (task.getTargetType() == 0){
					EventTerminals terminals = eventTerminalsService.findById(task.getTargetId());
					if (terminals!=null){
						planName = terminals.getTerminalName();
					}
				}
				if (task.getTargetType() == 1){
					EventPatrolPoint point = eventPatrolPointService.findById(task.getTargetId());
					if (point!=null){
						planName = point.getPatrolTitle();
					}
				}
				if (task.getTargetType() == 2){

				}
				if (task.getTargetType() == 3){

				}
				if (task.getTargetType() == 4){

				}
				if (task.getTargetType() == 5){
					planName = eventTerminalsService.findById(task.getTargetId()).getTerminalName();
				}
			}

			QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
			if(surveyUserRecord.getSurveyId()!=null){
				qw.eq("event_task_info_id",task.getId());
			}
			List<SurveyUserRecord> record = surveyUserRecordService.list(qw);
			if (record.size()>0){
				for (SurveyUserRecord record1:record){
					record1.setPlanName(planName);
					if (record1.getUserId()!=null){
						QueryWrapper<EstateUser> userQw = new QueryWrapper<>();
						userQw.eq("user_id",record1.getUserId());
						List<EstateUser> users = estateUserService.list(userQw);
						if (users.size()>0){
							record1.setNickName(users.get(0).getNickName());
						}
					}
					QueryWrapper<SurveyUserRecordInfo> qwInfo = new QueryWrapper<>();
					qwInfo.eq("record_id",record1.getId());
					List<SurveyUserRecordInfo> infoList = surveyUserRecordInfoService.list(qwInfo);
					int p = 0;
					for (SurveyUserRecordInfo info:infoList){
						if (info.getIsImg()!=1){
							if (info.getAnswer().equals(1)){
								p=1;
							}
						}
					}
					record1.setYichang(p);
					list.add(record1);
				}
			}
		}
		return list;
	}


	/**
	 * 通过workID查询问卷调查的用户填报数据列表
	 */
	@ApiOperation("查询问卷调查的用户填报数据列表")
	@PreAuthorize("@ss.hasPermi('module:survey_record:listWork')")
	@GetMapping("/listPointWork")
	public EventPointReturnList listPointWork(@Validated SurveyUserRecord surveyUserRecord) {
		EventPointReturnList pointList = new EventPointReturnList();
		List<BigDecimal> PointLng = new ArrayList<>();
		List<BigDecimal> PointLat = new ArrayList<>();
		List<BigDecimal> CenterPoint = new ArrayList<>();
		List<String> PointName = new ArrayList<>();
		List<Integer> PointId = new ArrayList<>();
		//查询taskInfo
		QueryWrapper<EventPlanTaskInfo> qwTask = new QueryWrapper<>();
		if (surveyUserRecord.getEventWorkId()!=null){
			qwTask.eq("event_work_id",surveyUserRecord.getEventWorkId());
		}
		List<EventPlanTaskInfo> taskList = eventPlanTaskInfoService.list(qwTask);

		for (EventPlanTaskInfo task:taskList){
			if (task.getTargetType()!=null&&task.getTargetId()!=null){
				if (task.getTargetType() == 0){
					EventTerminals point = eventTerminalsService.findById(task.getTargetId());
					PointLng.add(point.getLng());
					PointLat.add(point.getLat());
					PointName.add(point.getTerminalName());
					PointId.add(point.getId());
				}
				if (task.getTargetType() == 1){
					EventPatrolPoint point = eventPatrolPointService.findById(task.getTargetId());
					PointLng.add(point.getLng());
					PointLat.add(point.getLat());
					PointName.add(point.getPatrolTitle());
					PointId.add(point.getId());
				}
				if (task.getTargetType() == 2){

				}
				if (task.getTargetType() == 3){

				}
				if (task.getTargetType() == 4){

				}
				if (task.getTargetType() == 5){

				}
			}
		}
		//给中心点赋值
		if (taskList.get(0).getTargetType()!=null&&taskList.get(0).getTargetId()!=null){
			CenterPoint.add(taskList.get(0).getLng());
			CenterPoint.add(taskList.get(0).getLat());
		}
		pointList.setPointName(PointName);
		pointList.setCenterPoint(CenterPoint);
		pointList.setPointLat(PointLat);
		pointList.setPointLng(PointLng);
		pointList.setPointId(PointId);
		return pointList;
	}

	/**
	 * 通过planID查询问卷调查的用户填报数据列表
	 */
	@ApiOperation("查询问卷调查的用户填报数据列表")
	@PreAuthorize("@ss.hasPermi('module:survey_record:listPlan')")
	@GetMapping("/listPlan")
	public List<SurveyUserRecord> listPlan(@Validated SurveyUserRecord surveyUserRecord) {
		//返回值
		List<SurveyUserRecord> list = new ArrayList<>();
		//异常列表
		List<SurveyUserRecord> yichangList = new ArrayList<>();
		//查询全部记录
		QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
		qw.isNotNull("event_task_info_id");
		qw.orderByDesc("id");
		List<SurveyUserRecord> records = surveyUserRecordService.list(qw);
		//筛选问题记录
		for (SurveyUserRecord record : records){
			QueryWrapper<SurveyUserRecordInfo> qwInfo = new QueryWrapper<>();
			qwInfo.eq("record_id",record.getId());
			List<SurveyUserRecordInfo> infoList = surveyUserRecordInfoService.list(qwInfo);
			int p = 0;
			for (SurveyUserRecordInfo info:infoList){
				if (info.getIsImg()!=1){
					if (info.getAnswer().equals(1)){
						p=1;
						record.setYichang(p);
						yichangList.add(record);
					}
				}
			}
		}
		if (yichangList.size()>0){
			//通过planId查询全部task
			QueryWrapper<EventPlanTaskInfo> qwTask = new QueryWrapper<>();
			if (surveyUserRecord.getPlanId()!=null){
				qwTask.eq("event_plan_id",surveyUserRecord.getPlanId());
			}
			List<EventPlanTaskInfo> taskList = eventPlanTaskInfoService.list(qwTask);
			for (EventPlanTaskInfo task : taskList){
				for (SurveyUserRecord yichang:yichangList){
					if (yichang.getEventTaskInfoId()!=null){
						if (task.getId()==Math.toIntExact(yichang.getEventTaskInfoId())){
							list.add(yichang);
						}
					}
				}
			}
		}
		return list;
	}


    /**
     * 导出问卷调查的用户填报数据列表
     */
    @ApiOperation("导出问卷调查的用户填报数据列表")
    @PreAuthorize("@ss.hasPermi('module:survey_record:export')")
    @Log(title = "问卷调查的用户填报数据", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<SurveyUserRecord> export(@Validated SurveyUserRecord surveyUserRecord) {

		QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
		if(surveyUserRecord.getSurveyId() != null){
			qw.eq("survey_id",surveyUserRecord.getSurveyId());
		}
//		qw.orderByDesc("create_time");
        List<SurveyUserRecord> list = surveyUserRecordService.list(qw);

		if(CollUtil.isNotEmpty(list)) {
			for (SurveyUserRecord record : list){

				record.setCreateTimeStr(DateUtils.getTime(record.getCreateTime()));

				Estate estate = estateService.findById(record.getEstateId());
				if(estate!=null){
					record.setEstateName(estate.getEstateName());
				}

				Property property = propertyService.findById(record.getPropertyId());
				if(property!=null){
					record.setPropertyName(property.getPropertyName());
				}

				String roomName = "";
				String phoneNum = "";

				List<EstateRoom> rooms = estateRoomService.getRoomListByUserId(record.getUserId());
				if(CollUtil.isNotEmpty(rooms)){
					for (EstateRoom room : rooms){
						roomName += room.getRoomNo() + " ";
						if(StrUtil.isEmpty(record.getPhoneNum())){
							phoneNum += room.getPhoneNum();
						}
					}
				}
				if(StrUtil.isEmpty(record.getPhoneNum())) {
					record.setPhoneNum(phoneNum);
				}
				record.setRoomName(roomName);

				String answerContent = "";
				QueryWrapper<SurveyUserRecordInfo> qwInfo = new QueryWrapper<>();
				qwInfo.eq("record_id", record.getId());
				List<SurveyUserRecordInfo> recordInfos = surveyUserRecordInfoService.list(qwInfo);
				for (SurveyUserRecordInfo recordInfo1 : recordInfos){
					SurveyQuestion question = surveyQuestionService.getById(recordInfo1.getQuestionId());
					if(question != null){
						if (question.getQuestionType()==0){
							if(StrUtil.isNotEmpty(question.getAnswerSection())){
								JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
								JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(Integer.parseInt(recordInfo1.getAnswer())));
								if(jsonObject != null){
									answerContent +=  question.getQuestion() +  " => " + jsonObject.getStr("value") + "； \r\n";
								}
							}
						}else if (question.getQuestionType()==1){
							answerContent +=  question.getQuestion() +  " => " + recordInfo1.getAnswer() + "； \r\n";
						}else {
							answerContent +=  question.getQuestion() +  " => " + imgUrl +recordInfo1.getAnswer() + "； \r\n";
						}

					}
				}

				record.setAnswerContent(answerContent);
				QueryWrapper<SurveyUserRecordInfo> qwInfos = new QueryWrapper<>();
				qwInfos.eq("record_id",record.getId());
				List<SurveyUserRecordInfo> infoList = surveyUserRecordInfoService.list(qwInfos);
				int p = 0;
				for (SurveyUserRecordInfo info:infoList){
					if (info.getIsImg()!=1){
						if (info.getAnswer().equals(1)){
							p=1;
						}
					}
				}
				record.setYichang(p);
			}
		}
        ExcelUtil<SurveyUserRecord> util = new ExcelUtil<SurveyUserRecord>(SurveyUserRecord.class);
        return util.exportExcel(list, "问卷调查的用户填报数据");
    }

    /**
     * 获取问卷调查的用户填报数据详细信息
     */
    @ApiOperation("获取问卷调查的用户填报数据详细信息")
    @PreAuthorize("@ss.hasPermi('module:survey_record:query')")
    @GetMapping("/{id}")
    public AjaxResult<SurveyUserRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        SurveyUserRecord surveyUserRecord = surveyUserRecordService.getById(id);
        return AjaxResult.success(surveyUserRecord);
    }

    /**
     * 新增问卷调查的用户填报数据
     */
    @ApiOperation("新增问卷调查的用户填报数据")
    @PreAuthorize("@ss.hasPermi('module:survey_record:add')")
    @Log(title = "问卷调查的用户填报数据", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody SurveyUserRecord surveyUserRecord) {
        return toAjax(surveyUserRecordService.save(surveyUserRecord) ? 1 : 0);
    }

    /**
     * 修改问卷调查的用户填报数据
     */
    @ApiOperation("修改问卷调查的用户填报数据")
    @PreAuthorize("@ss.hasPermi('module:survey_record:edit')")
    @Log(title = "问卷调查的用户填报数据", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody SurveyUserRecord surveyUserRecord) {
        return toAjax(surveyUserRecordService.updateById(surveyUserRecord) ? 1 : 0);
    }

    /**
     * 删除问卷调查的用户填报数据
     */
    @ApiOperation("删除问卷调查的用户填报数据")
    @PreAuthorize("@ss.hasPermi('module:survey_record:remove')")
    @Log(title = "问卷调查的用户填报数据" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(surveyUserRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
